package ter.find.pattern.gui;

import java.awt.Color;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;

import ter.find.pattern.BaseTableModel;

public class BasePanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable table;
    private JTextField filterText;
    private JTextField statusText;
    private TableRowSorter<BaseTableModel> sorter;
    public static ArrayList<Integer> listIdSeq=new ArrayList<Integer>();;

    public BasePanel(BaseTableModel contentBaseModel) {
        super();
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        this.setVisible(true);
        
        sorter = new TableRowSorter<BaseTableModel>(contentBaseModel);
        table = new JTable(contentBaseModel);
        table.setRowSorter(sorter);
        
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        ListSelectionModel cellSelectionModel = table.getSelectionModel();
        cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            Object selectedData = null;

            int[] selectedRow = table.getSelectedRows();
            int[] selectedColumns = table.getSelectedColumns();
            int row=0,col=0;
            for (int i = 0; i < selectedRow.length; i++) {
              for (int j = 0; j < selectedColumns.length; j++) {
                selectedData = table.getValueAt(selectedRow[i], selectedColumns[j]);
                row=selectedRow[i];
                col=selectedColumns[i];
              }
            }
            
            
            if(col==1 && (boolean)selectedData){
            	
            	System.out.println("case Cocher");
            	System.out.println("Ligne ajoutée"+row);            	
            	Integer number=new Integer(row);            	
            	listIdSeq.add(number);   
            	removeDuplicates(listIdSeq);
            	
            }
            if(col==1 && !(boolean)selectedData){
            	System.out.println("case décochée "+row);           	
            	
            			try {
            				for(Integer i:listIdSeq){
                        		if(i==row){
                        			System.out.println("élément dans la liste "+i);
                        			listIdSeq.remove((Integer)i);
                        			System.out.println("élément supprimé dans la liste "+i);
                        		}
            				}
						} catch (ConcurrentModificationException e1) {
							// TODO Auto-generated catch block
							System.out.println("Warning");
						}
            			
            		
            	
            	if(!listIdSeq.isEmpty()){
            		for(int j=0;j<listIdSeq.size();j++){
            			System.out.println(listIdSeq.get(j));
            		}
            	}else{
                	System.out.println("Liste vide");

            	}
            	
            	
            	
            }
            
            //System.out.println(row);
            //System.out.println("Selected: " + selectedData);
          }

        });
        
        elementCenter(table);
        fixedWidthCol(table, 0, 100);
        fixedWidthCol(table, 1, 30);
        fixedWidthCol(table, 2, 850);
        
        
        //When selection changes, provide user with row numbers for
        //both view and model.
        table.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent event) {
                        int viewRow = table.getSelectedRow();
                        if (viewRow < 0) {
                            //Selection got filtered away.
                            statusText.setText("");
                        } else {
                        	int[] selectedRow = table.getSelectedRows();
                            int[] selectedColumns = table.getSelectedColumns();
                            for (int i = 0; i < selectedRow.length; i++) {
                                for (int j = 0; j < selectedColumns.length; j++) {
                                	statusText.setText(table.getValueAt(selectedRow[i], selectedColumns[j]).toString());
                                  
                                }
                              }
                        }
                    }
                }
        );

        colorHead(table, Color.blue);
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);

        //Create a separate form for filterText and statusText
        JPanel form = new JPanel(new SpringLayout());
        JLabel l1 = new JLabel("Find Id séquence:", SwingConstants.TRAILING);
        form.add(l1);
        filterText = new JTextField();
        //Whenever filterText changes, invoke newFilter.
        filterText.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        newFilter();
                    }
                    public void insertUpdate(DocumentEvent e) {
                        newFilter();
                    }
                    public void removeUpdate(DocumentEvent e) {
                        newFilter();
                    }
                });
        l1.setLabelFor(filterText);
        form.add(filterText);
        JLabel l2 = new JLabel("Selection:", SwingConstants.TRAILING);
        form.add(l2);
        statusText = new JTextField();
        l2.setLabelFor(statusText);
        form.add(statusText);
        SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
        add(form);
    }
    
    public static void removeDuplicates(List<Integer> list)  
    {  
      Set<Object> uniqueEntries = new HashSet<Object>();  
      for (Iterator<Integer> iter = list.iterator(); iter.hasNext(); ) {  
        Object element = iter.next();  
        if (!uniqueEntries.add(element)) // if current element is a duplicate,  
          iter.remove();                 // remove it  
      }  
    }
    
    public void fixedWidthCol(JTable tab,int colIndex,int colWidth ){
    	tab.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         TableColumn col = tab.getColumnModel().getColumn(colIndex);         
         col.setPreferredWidth(colWidth);
    }
    
    public void elementCenter(JTable tab){
    	DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    	centerRenderer.setHorizontalAlignment( JLabel.CENTER );
    	tab.setDefaultRenderer(String.class, centerRenderer);
    }
    
    public void colorHead(JTable tab,Color c){
		JTableHeader header = tab.getTableHeader();
		header.setBackground(c);
		header.setForeground(Color.gray);
		header.setOpaque(true);
	}
    
    public static List<Integer> getListIdseq(){
    	return listIdSeq;
    }

    /** 
     * Update the row filter regular expression from the expression in
     * the text box.
     */
    private void newFilter() {
        RowFilter<BaseTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            rf = RowFilter.regexFilter(filterText.getText(), 0);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }



}
